var express = require('express');
var router = express.Router();
const userMoudel = require('../module/usermodule');
const md5 = require('md5');
const jwt = require('jsonwebtoken');



/* GET users listing. */
router.get('/reg', function(req, res, next) {
    res.render('reg');
  });

  // 注册 
router.post('/reg', function(req, res, next) {

  console.log(req.body);
  // db.get('accounts').push(req.body).write();
  userMoudel.create({...req.body,password:md5(req.body.password)}).then((data)=>{
    res.send({
      code : 200 ,
      msg : '添加成功',
      data : data
    });
  }).catch((err)=>{
      console.log(err);
      res.send({
        code : 500 ,
        msg : err,
        data : {}
      });
  });


});

// 登录
router.post('/login', function(req, res, next) {

  console.log(req.body);
  let {username,password} = req.body ; 
  userMoudel.findOne({username : username,password:md5(req.body.password)}).then((data)=>{  
    console.log(req.session);

    // req.session.username = data.username ; 
    // req.session._id = data._id ; 

    let token = jwt.sign({
      username : data.username 
    },'atguigu',{
      expiresIn : 60 * 60 * 24 * 7 
    }); 

    res.json({
      code : 200 ,
      msg : '登录成功·····',
      token : token 

    });

    // res.render('result',{
    //   msg:'登录成功',
    //     url : '/account/list'
    // });



  }).catch((err)=>{
      console.log(err);
      res.json({
        code : 500 ,
        msg : err,
        data : {}
      });
  });


});


// 登出
router.get('/logout', function(req, res, next) {
    req.session.destroy(()=>{
      res.render('result',{
        msg:'退出成功',
        url : '/login'
      });
    });

});

module.exports = router ; 

